<template>
    <div
        :class="['w-full p-24 box-border', { 'min-loading-height': isLoading }]"
        v-loading="isLoading"
        element-loading-text="加载中....."
    >
        <template v-if="!isLoading">
            <!-- 顶部 -->
            <PageHeader
                title="文章列表"
                v-model="headerPopoverVisible"
                is-need-screen
                :is-data-loading="isLoading"
                @refresh="resetList"
                @search="getArticleList"
            >
                <!-- 搜索表单 -->
                <SearchBox type='left' title="文章标题">
                    <el-input v-model="searchParams.articleTitle" placeholder="请输入文章标题" clearable/>
                </SearchBox>
                <SearchBox type='right' title="发布状态">
                    <el-select
                        v-model="searchParams.releaseStatus"
                        class="w-full"
                        clearable
                        placeholder="请选择发布状态"
                        :teleported="false"
                    >
                        <el-option
                            v-for="({ label, value }) in releaseStatusList"
                            :key="value"
                            :label="label"
                            :value="value"
                            @click.native.stop
                        />
                    </el-select>
                </SearchBox>
                <!-- 自定义按钮 -->
                <template #custom>
                    <el-button type="primary" round @click="toPage('add')">
                        <Icon name="Plus" class="mr-6"/>新增文章
                    </el-button>
                </template>
            </PageHeader>
            <!-- 无数据 -->
            <template v-if="isNoData"><Empty/></template>
            <!-- 内容 -->
            <template v-else>
                <div class="w-full bg-white p-24 card-style common-shadow">
                    <!-- 表格 -->
                    <el-table :data="articleList" class="w-full">
                        <!-- 文章封面 -->
                        <el-table-column label="文章封面">
                            <template v-slot="{ row }">
                                <el-image
                                    class="article-picture my-10 cursor-pointer rounded-4"
                                    :src="row.articlePictureList[0].url"
                                    fit="cover"
                                    @click="toPage('see', row.articleId)"
                                />
                            </template>
                        </el-table-column>
                        <!-- 文章标题 -->
                        <el-table-column label="文章标题" width="220">
                            <template v-slot="{ row }">
                                <div class="cursor-pointer" @click="toPage('see', row.articleId)">{{ row.articleTitle }}</div>
                            </template>
                        </el-table-column>
                        <!-- 作者 -->
                        <el-table-column label="作者" prop="author" />
                        <!-- 点赞数 -->
                        <el-table-column label="点赞数" prop="likeCount" />
                        <!-- 浏览量 -->
                        <el-table-column label="浏览量" prop="viewCount" />
                        <!-- 浏览量 -->
                        <el-table-column label="文章状态">
                            <template v-slot="{ row }">
                                {{ row.releaseStatus ? '已发布' : '未发布' }}
                            </template>
                        </el-table-column>
                        <!-- 创建时间 -->
                        <el-table-column label="创建时间" prop="createdTime" width="200"/>
                        <!-- 可执行操作 -->
                        <el-table-column label="操作" align="right" width="250">
                            <template #default="{ row }">
                                <!-- 编辑 -->
                                <el-button round @click="toPage('edit', row.articleId)">编辑</el-button>
                                <!-- 撤回 / 重新发布 -->
                                <el-button
                                    round
                                    type="primary"
                                    @click="handleWithdrawRelease(row.articleId, row.releaseStatus ? 0 : 1)"
                                >
                                    {{ row.releaseStatus ? '撤回' : '发布' }}
                                </el-button>
                                <!-- 删除 -->
                                <el-popconfirm @confirm="handleDelete(row.articleId)" title="是否确认删除这篇文章？">
                                    <template #reference>
                                        <el-button round type="danger">删除</el-button>
                                    </template>
                                </el-popconfirm>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <!-- 分页 -->
                <div class="flex-center-box w-full mt-20">
                    <el-pagination
                        v-model:current-page="pageParams.currentPage"
                        v-model:page-size="pageParams.currentSize"
                        background
                        :hide-on-single-page="pageParams.total <= pageParams.currentSize"
                        layout="total, prev, pager, next, jumper, sizes"
                        :total="pageParams.total"
                        :page-sizes="[8, 16, 24]"
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                    />
                </div>
            </template>
        </template>
    </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ArticleDetail,
    ArticleList,
    httpArticleList,
    httpDeleteArticle,
    httpUpdateArticleStatus,
    ReleaseStatus } from '@api/module/brandPromotion'
import { PageParams, PageTypeKey } from '@/type/common'
import { ElMessages, timeout } from '@utils/methods'

// 组件
import PageHeader from '@/components/PageHeader/index.vue'
import Icon from '@/components/Icon/index.vue'
import SearchBox from '@components/SearchBox/index.vue'
import Empty from '@components/Empty/index.vue'

// 路由
const router = useRouter()

// 页面加载
const isLoading = ref(false)

// 筛选条件弹窗状态
const headerPopoverVisible = ref(false)

// 无数据
const isNoData = ref(false)

// 发布状态
interface ReleaseStatusList {
    /** @description 状态文本 */
    label: string
    /** @description 状态值 0 未发布 1 已发布 */
    value: 0 | 1
}

// 发布状态
const releaseStatusList: ReleaseStatusList[] = [
    { label: '已发布', value: 1 },
    { label: '未发布', value: 0 }
]

// 跳转新增 / 编辑 / 详情
const toPage = (pageType: PageTypeKey, articleId?: number) => {
    router.push({
        path: '/BrandPromotion/ArticleDetail',
        query: {
            pageType,
            articleId: articleId || ''
        }
    })
}

// 文章列表
const articleList = ref<ArticleDetail[]>([])

// 查询内容
const searchParams = reactive<ArticleList>({
    articleTitle: '',
    releaseStatus: null
})

// 分页
const pageParams = reactive<PageParams>({
    currentPage: 1,
    currentSize: 8,
    total: null
})

// 撤回 / 重新发布文章
const handleWithdrawRelease = (articleId: number, releaseStatus: ReleaseStatus) => {
    httpUpdateArticleStatus({
        articleId,
        releaseStatus
    }).then(({ success }) => {
        if (success) {
            ElMessages.success(!releaseStatus ? '撤回成功!' : '发布成功!')
            getArticleList()
        }
    })
}

// 删除文章
const handleDelete = (articleId: number) => {
    httpDeleteArticle({ articleId }).then(({ success }) => {
        if (success) {
            ElMessages.success('删除成功')
            // 如果列表只有一条数据，请求上一页数据
            if (articleList.value.length === 1) pageParams.currentPage--
            getArticleList()
        } else {
            ElMessages.error('删除失败！请重试')
        }
    })
}

// 获取文章列表
const getArticleList = () => {
    isLoading.value = true
    httpArticleList({
        ...searchParams,
        ...pageParams
    }).then(res => {
        isNoData.value = !res.data.total
        if (res.data.total) {
            articleList.value = res.data.list
            pageParams.total = res.data.total
        } else {
            articleList.value = []
        }
    }).finally(async () => {
        headerPopoverVisible.value = false
        await timeout(500)
        isLoading.value = false
    })
}

getArticleList()

/**
 * 重置数据
 * */
const resetList = () => {
    pageParams.currentPage = 1
    pageParams.currentSize = 8
    searchParams.articleTitle = ''
    searchParams.releaseStatus = null
    getArticleList()
}

// 当前页码改变
const handleCurrentChange = (currentPage: number) => {
    pageParams.currentPage = currentPage
    getArticleList()
}

// 条数改变
const handleSizeChange = (currentSize: number) => {
    pageParams.currentSize = currentSize
    pageParams.currentPage = 1
    getArticleList()
}
</script>

<style lang="less" scoped>
.article-picture{
    width: 100px;
    height: 100px;
}

:deep(.el-table__body-wrapper) {
    --el-table-border: none;
}

:deep(.el-table__header-wrapper) {
    --el-table-border: none;
    padding-bottom: 12px;
    font-size: 15px;
}

:deep(.el-table__inner-wrapper::before){
    height: 0;
}
</style>
